<template>
    <div id="univereditor1" style="height:93vh">
       
    </div>
    
</template>

<script>
   import * as signalR from '@microsoft/signalr';
   import "@univerjs/design/lib/index.css";
  import "@univerjs/ui/lib/index.css";
  import "@univerjs/docs-ui/lib/index.css";
  import "@univerjs/sheets-ui/lib/index.css";
  import "@univerjs/sheets-formula/lib/index.css";
  import { IWorkbookData, UniverInstanceType, CommandType,ICommand,ICommandService  } from "@univerjs/core";
  import { LocaleType, Tools, Univer } from "@univerjs/core";
  import { defaultTheme } from "@univerjs/design";
  
  import { UniverFormulaEnginePlugin } from "@univerjs/engine-formula";
  import { UniverRenderEnginePlugin } from "@univerjs/engine-render";
  
  import { UniverUIPlugin } from "@univerjs/ui";
  import { diyplugin } from "../common/diyplugin.js";

  import { UniverDocsPlugin } from "@univerjs/docs";
  import { UniverDocsUIPlugin } from "@univerjs/docs-ui";
  
  import { UniverSheetsPlugin } from "@univerjs/sheets";
  import { UniverSheetsFormulaPlugin } from "@univerjs/sheets-formula";
  import { UniverSheetsUIPlugin } from "@univerjs/sheets-ui";
  import { FUniver } from "@univerjs/facade";
  import DesignZhCN from '@univerjs/design/locale/zh-CN';
  import UIZhCN from '@univerjs/ui/locale/zh-CN';
  import DocsUIZhCN from '@univerjs/docs-ui/locale/zh-CN';
  import SheetsZhCN from '@univerjs/sheets/locale/zh-CN';
  import SheetsUIZhCN from '@univerjs/sheets-ui/locale/zh-CN';

    export default {
    name: 'univer-editor',
    data(){
      return{
        univerdata:null,
        IWorkbookData:{},
        connection:null,
        isload:false,
       
      }
    },
   
    props: {
      data: Object,
      backmain:Function,
    },
    methods:{
      clickdata(){
        const univerAPI = FUniver.newAPI(this.univer);
        const activeWorkbook = univerAPI.getActiveWorkbook()
        const saveData = activeWorkbook.getSnapshot();

      },
      loaddata(){
        var taht=this;
        this.connection.invoke('GetLoadData', "2")
        setTimeout(() => {
          const univerAPI = FUniver.newAPI(this.univer);
          const activeWorkbook = univerAPI.getActiveWorkbook()
          const saveData = activeWorkbook.getSnapshot();
          
          this.connection.invoke('SaveData', JSON.stringify(saveData))
        }, 3000);
      
      },
 
      register(univer){
        
        univer.registerPlugin(UniverRenderEnginePlugin);
        univer.registerPlugin(UniverFormulaEnginePlugin);
        
        univer.registerPlugin(UniverUIPlugin, {
          container: 'univereditor1',
        });
        
        univer.registerPlugin(UniverDocsPlugin, {
          hasScroll: false,
        });
        univer.registerPlugin(UniverDocsUIPlugin);
        
        univer.registerPlugin(UniverSheetsPlugin);
        univer.registerPlugin(UniverSheetsUIPlugin);
        univer.registerPlugin(UniverSheetsFormulaPlugin);
        univer.registerPlugin(diyplugin);
        const univerAPI = FUniver.newAPI(univer);
        // URL 换成你自己 Websocket 服务的地址
        //创建连接
        let url=this.$apiUrl;
     
        this.connection = new signalR.HubConnectionBuilder()
          // .withUrl(url+"/UniverjsEditing") // 替换为你的SignalR服务URL
          .withUrl("/socketcon/UniverjsEditing") // 替换为你的SignalR服务URL
          .configureLogging(signalR.LogLevel.Information) 
          .build();
                 
        //响应加载回调
        this.connection.on('ReceiveLoad', res=>{
          if(res==null){
            return;
          }
          if(this.isload){
            return;
          }
          this.isload=true;
        
          
          univer.createUnit(UniverInstanceType.UNIVER_SHEET, 
            JSON.parse(res)
          );
        }); 
        //响应回调
        this.connection.on('ReceiveServerResponse', res=>{
          
        });
        //响应发送所有人消息
        this.connection.on('SendAllMessage', res=>{
          
        });
         //响应发送所有人消息
        this.connection.on('GetLoadDataCache', res=>{
          const univerAPI = FUniver.newAPI(this.univer);
          const activeWorkbook = univerAPI.getActiveWorkbook()
          const saveData = activeWorkbook.getSnapshot();
          var data={connectionId:res,data:saveData}
          this.connection.invoke('SendLoadDataCache', JSON.stringify(data))
        });
        //响应发送其他人
        this.connection.on('SendOtherMessage', content=>{
          if (!content.includes('command')) {
            return
          }
          const commandInfo = JSON.parse(content);
          const { command, options } = commandInfo;
          const { id, params } = command;
        
          // 接受到协同数据，本地落盘
          univerAPI.executeCommand(id, params, options)
        });
        //开始连接
        this.connection.start().then(()=>{
           this.loaddata();
        });
        //注册事件
        const activeWorkbook = univerAPI.getActiveWorkbook();
        univerAPI.onCommandExecuted((command,options)=>{
          if(command.id=="back-button"){
            this.backmain();
          }
          if (command.type !== 2 || options?.fromCollab || options?.onlyLocal || command.id === 'doc.mutation.rich-text-editing') 
          {
            return;
          }
          const commandInfo = JSON.stringify({ command, options: { fromCollab: true } })
          this.connection.invoke('SendMessageToServer', commandInfo)
        
        })
        

      },
    },
    created(){
      
    },
    mounted(){
       this.univer= new Univer({
        theme: defaultTheme,
        locale: LocaleType.ZH_CN,
        locales: {
          [LocaleType.ZH_CN]: Tools.deepMerge(
            SheetsZhCN,
            DocsUIZhCN,
            SheetsUIZhCN,
            UIZhCN,
            DesignZhCN,
          ),
        },
      });
      this.register(this.univer);
    
    },
  }
  </script>
